/*
 * @(#)MaintFormSectionAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.form.bean.FormElement;
import com.dcivision.form.bean.FormSection;
import com.dcivision.form.bean.MtmFormPageFormSection;
import com.dcivision.form.bean.MtmFormSectionFormElement;
import com.dcivision.form.dao.FormElementDAObject;
import com.dcivision.form.dao.FormSectionDAObject;
import com.dcivision.form.dao.MtmFormPageFormSectionDAObject;
import com.dcivision.form.dao.MtmFormSectionFormElementDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;

/**
  MaintFormSectionAction.java

  This class is for maint user record.

    @author          Scott Tong
    @company         DCIVision Limited
    @creation date   10/12/2003
    @version         $Revision: 1.16 $
*/

public class MaintFormSectionAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.16 $";

  protected String listName = "";
  public MaintFormSectionAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.form.dao.FormSectionDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.FORM_SETUP);
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    AbstractActionForm maintForm = (AbstractActionForm)form;

    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();
    String navMode = (maintForm!=null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();

    if (GlobalConstant.OP_MODE_REFRESH.equals(opMode)) {
      // Set the function code for current action.
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
        return forward;
      }
      refreshFormData(mapping, maintForm, request, response);
      return mapping.findForward(GlobalConstant.NAV_MODE_REFRESH);
    } else {
      return super.execute(mapping, form, request, response);
    }
  }

  public void refreshFormData(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    List resultList = new ArrayList();

    try {
      SessionContainer sessionCon = this.getSessionContainer(request);
      MaintFormSectionForm formSectionForm = (MaintFormSectionForm)form;
      int listSize = 0;
      int intNewField =0;
      try {
        listSize = TextUtility.parseInteger(request.getParameter("listSize"));
        intNewField = TextUtility.parseInteger(request.getParameter("newField"));
      } catch (Exception e) {
        throw new ApplicationException (ErrorConstant.COMMON_FATAL_ERROR, e);
      }

      int sum=0;
      sum=listSize+intNewField;

      //Get Header Form data
      FormSection formSection = (FormSection)formSectionForm.getFormData();

      //Set Header Form data
      formSectionForm.setFormData(formSection);

      for (int i = 0; i < listSize; i++){
        FormElement tmpFormElement = new FormElement();
        if (!("".equals(request.getParameter("formElementID_"+i))) && !("null".equals(request.getParameter("formElementID_"+i))))
            tmpFormElement.setID(new Integer(request.getParameter("formElementID_"+i)));
        if (!("".equals(request.getParameter("formElementName_"+i))) && (!"null".equals(formSection.getID())))
          tmpFormElement.setFieldName(new String (request.getParameter("formElementName_"+i)));

        String strMandatoryCheckValue = request.getParameter("mandatory_"+i);
        if (strMandatoryCheckValue == null){
          tmpFormElement.setRequiredFlag("N");
        } else {
          tmpFormElement.setRequiredFlag("Y");
        }

        String strElementTypeChooseValue = request.getParameter("formElementType_"+i);
        tmpFormElement.setElementType(strElementTypeChooseValue);
        String strDeleteCheckValue = request.getParameter("delete_"+i);
        if (strDeleteCheckValue == null){
          resultList.add(tmpFormElement);
        }
      }
      formSectionForm.setFormElementListData(resultList);
      formSectionForm.setFormElementList(formSectionForm.getFormElementList());

      request.setAttribute("listSize", new Integer(listSize));
      request.setAttribute("newFieldsSize", new Integer(sum));
      request.setAttribute("newField", new Integer(intNewField));
    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e){
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {
    }
  }

  public void refreshList(HttpServletRequest request, String opMode, com.dcivision.framework.bean.AbstractBaseObject obj) {
    java.util.ArrayList list = (java.util.ArrayList)request.getAttribute(this.listName);
    if (list != null) {
      if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
        list.add(obj);
      } else if (GlobalConstant.OP_MODE_UPDATE.equals(opMode)) {
        for (int i = 0; i < list.size(); i++) {
          if (obj.equals(list.get(i))) {
            list.remove(i);
            list.add(i, obj);
          }
        }
      } else if (GlobalConstant.OP_MODE_DELETE.equals(opMode)) {
        for (int i = 0; i < list.size(); i++) {
          if (obj.equals(list.get(i))) {
            list.remove(i);
          }
        }
      }
    }
  }

  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    try {
      MaintFormSectionForm formSectionForm = (MaintFormSectionForm)form;
      String fieldName = formSectionForm.getFieldName();
      //get form section
      Integer FormSectionID = TextUtility.parseIntegerObj(formSectionForm.getID());
      FormSectionDAObject formSectionDAO = new FormSectionDAObject(this.getSessionContainer(request), this.getConnection(request));
      FormSection formSection = (FormSection)formSectionDAO.getObjectByID(FormSectionID);
      formSectionForm.setFormData(formSection);
      //set the title of FormSection that it is field value in EditFormSectionFormElement.jsp file. 
      if(!Utility.isEmpty(fieldName)){
        formSectionForm.setFieldName(fieldName);
      }
      //get form element
      FormElementDAObject FormElementDAO = new FormElementDAObject(this.getSessionContainer(request), this.getConnection(request));
      List formElementList = FormElementDAO.getListByFormSectionID(formSection.getID());
      formSectionForm.setFormElementListData(formElementList);

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
    } finally {}
  }


  public void insertRecord(ActionMapping mapping, AbstractActionForm form,HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintFormSectionForm formSectionForm = (MaintFormSectionForm)form;
    String fontStyle="";
    if (request.getParameter("fontStyleBold") != null)
      fontStyle += "B";
    if (request.getParameter("fontStyleUnderline") != null)
      fontStyle += "U";
    if (request.getParameter("fontStyleItalic") != null)
      fontStyle += "I";
    formSectionForm.setsectionFontStyle(fontStyle);
    formSectionForm.setSubSection("N");
    super.insertRecord(mapping, formSectionForm, request, response);

  }

  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintFormSectionForm formSectionForm = (MaintFormSectionForm) form;
    String fontStyle = "";
    if (request.getParameter("fontStyleBold") != null)
      fontStyle += "B";
    if (request.getParameter("fontStyleUnderline") != null)
      fontStyle += "U";
    if (request.getParameter("fontStyleItalic") != null)
      fontStyle += "I";
    formSectionForm.setsectionFontStyle(fontStyle);
    formSectionForm.setSubSection("N");
    super.updateRecord(mapping, formSectionForm, request, response);

  }

  public void deleteRecord(ActionMapping mapping,
                           AbstractActionForm form,
                           HttpServletRequest request,
                           HttpServletResponse response) throws ApplicationException {
    MaintFormSectionForm formSectionForm = (MaintFormSectionForm) form;
    String formPageID = "";
    String delSectionID = "";  
    Integer preSectionID = new Integer(-1);
    formPageID = request.getParameter("formPageID");
    delSectionID = formSectionForm.getID();
    int delSectionSeq = 0;
    int preSectionSeq = 0;
    MtmFormPageFormSection mtmFormPageFormSection = new MtmFormPageFormSection();
    MtmFormPageFormSectionDAObject mtmFormPageFormSectionDAO =
        new MtmFormPageFormSectionDAObject(this.getSessionContainer(request),
                                           this.getConnection(request));
    MtmFormSectionFormElementDAObject mtmFormSectionFormElementDAO =
        new MtmFormSectionFormElementDAObject(this.getSessionContainer(request),
                                              this.getConnection(request));
    FormSectionDAObject formSectionDAO = new FormSectionDAObject(
        this.getSessionContainer(request), this.getConnection(request));

    // Get the seqNo of deleted section
    mtmFormPageFormSection = (MtmFormPageFormSection)mtmFormPageFormSectionDAO.
        getObjectByPageIDSectionID(new Integer(formPageID),new Integer(delSectionID));
    delSectionSeq = (mtmFormPageFormSection.getSectionSeq()).intValue();
    if (delSectionSeq != 0){
      // Get all sections of page [formPageID]
      List mtmFormPageFormSectionList = mtmFormPageFormSectionDAO.
          getListByPageID(new Integer(formPageID));
      // Get the previous section at the deleted section
      for (int i = mtmFormPageFormSectionList.size()-1; i >= 0;i--) {
        if (i <0) { break;}
        MtmFormPageFormSection tmpMtmFormPageFormSection =
            (MtmFormPageFormSection)mtmFormPageFormSectionList.get(i);
        if (tmpMtmFormPageFormSection.getSectionSeq().intValue() < delSectionSeq) {
          preSectionID = tmpMtmFormPageFormSection.getSectionID();
          preSectionSeq = tmpMtmFormPageFormSection.getSectionSeq().intValue();

          // Get last element seqNO of pre section.
          List mtmFormSectionFormElementList = mtmFormSectionFormElementDAO.
              getListBySectionID(preSectionID);
          MtmFormSectionFormElement lastMtmFormSection = (
              MtmFormSectionFormElement)(mtmFormSectionFormElementList.get(
              mtmFormSectionFormElementList.size()-1));
          Integer lastElementSeq = lastMtmFormSection.getElementSeq();
          // Update all Elements's seqNo of pre section
          List delElementList = mtmFormSectionFormElementDAO.getListBySectionID(
              new Integer(delSectionID));
          for (int j = 0; j < delElementList.size(); j++) {
            MtmFormSectionFormElement tmpUpdateMtmSectionElement =
                (MtmFormSectionFormElement)delElementList.get(j);
            tmpUpdateMtmSectionElement.setElementSeq(
                new Integer(lastElementSeq.intValue()+j+1));
            tmpUpdateMtmSectionElement.setSectionID(preSectionID);
            mtmFormSectionFormElementDAO.updateObject(tmpUpdateMtmSectionElement);
          }
        }
      }
      // Delete section in MTM_FORM_PAGE_FORM_SECTION table
      mtmFormPageFormSectionDAO.deleteObject(mtmFormPageFormSection);

      // Delete section in FORM_SECTION table
      formSectionDAO.deleteObjectByID(new Integer(delSectionID));

    }
  }

}